$(function () {
    var queryUrl = '../devAmPlan/list';
    var planId = getQueryString('Id');
    if (planId) {
        queryUrl += '?planId=' + planId
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '计划名称', name: 'planName', index: 'PLAN_NAME', width: 120, align: 'center'},
            {
                label: '计划起始时间', name: 'startDate', index: 'START_DATE', width: 80, align: 'center',
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd");
                }
            },
            {
                label: '计划结束时间', name: 'endDate', index: 'END_DATE', width: 80, align: 'center',
                formatter: function (value) {
                    return transDate(value, "yyyy-MM-dd");
                }
            },
            {label: '所属车间', name: 'workshopName', index: 'WORKSHOP', width: 80, align: 'center'},
            {label: '排除区间', name: 'excludeRange', index: 'EXCLUDE_RANGE', align: 'center'},
            {label: '编制人', name: 'createUserName', index: 'dmp.CREATE_USER', width: 80, align: 'center'},
            {label: '评审人', name: 'approverName', index: 'APPROVER', width: 80, align: 'center'},
            {
                label: '状态', width: 60, align: 'center', index: 'dmp.STATUS',
                formatter: function (value, col, row) {
                    if (row.status == null || row.status == "null") {
                        return "暂无"
                    } else {
                        return sysEnums.SPARE_NEEDS_PLAN_PROGRESS[row.status];
                    }
                }
            },
            {label: '备注', name: 'remark', index: 'REMARK', align: 'center'},
            {
                label: '规程', width: 40, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.addPlanOp(\"" + row.id + "\",\"" + row.status + "\")'><i class='fa fa-plus'></i></button>";
                }
            },
            {
                label: '调整', width: 40, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.planChange(\"" + row.id + "\",\"" + row.status + "\")'><i class='fa fa-wrench'></i></button>";
                }
            },
            {
                label: '详情', width: 40, sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' id='recordsText' onclick='vm.viewPlan(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {name: 'status', hidden: true},
            {name: 'id', index: 'ID', key: true, hidden: true},
        ]
    });
    // 加载设备产线列表数据
    vm.loadDevLineListData();
    // 加载设备组织结构树
    vm.initDevOrgTree();
});

// 车间产线选择树插件配置参数
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    },
    callback: {
        beforeCheck: true
    }

};

//首页左侧设备组织结构树
var deptSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl",
            name: "complexName"
        }
    },
    callback: {
        beforeCheck: true,
        beforeClick: outTreeCheck
    }
};

function outTreeCheck(e, treeObj, treeNode) {
    vm.q.deptCode = treeObj.deptId;
    vm.query();
}

let vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        showPreview: false, // 展示设备维护计划概览
        title: null,
        devPlanMain: {
            startDate: '',
            endDate: '',
            remark: '',
            planName: '',
            devLineId: '',
            devLineName: '',
            excludeRange: '',
            id: ''
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        freRateArray: enumsToList("FRERATE"),
        typeList: enumsToList('MAINTENPLAN_TYPE'),//类型
        q: {
            planName: '',
            deptCode: '',
            yearly: ''
        },
        // 维护计划概览参数
        overviewParam: {
            yearly: '',
            action: 'download'
        },
        // 审核参数VO
        approveParam: {
            approveIdList: [],
            status: 1,
            remark: ''
        },
        generateMaintenanceTicketDate: '', // 生成工单日期
        selectedPlanIds: '', // 已选中的设备维护计划ID字符串
        selectedPlanList: '' // 已选中的设备维护计划名称列表
    },
    methods: {
        //加载列表页树
        initDevOrgTree: function () {
            deptZtree = $.fn.zTree.init($("#storeTree"), deptSetting, vm.treeList);
            // 默认展开工厂一级
            deptZtree.expandNode(deptZtree.getNodeByParam("deptId", '01', null));
            //deptZtree.expandAll(true);
        },
        // 展示设备维护计划概览
        showOrHidePreviewForm: function () {
            // 初始化计划概览变量
            vm.selectedPlanIds = '';
            vm.selectedPlanList = '';
            // 默认展示年度的，否则展示选中的
            vm.selectedPlanIds = getSelectedRows('#jqGrid');
            if (vm.selectedPlanIds) {
                var planList = getSelectedRowDatas('#jqGrid');
                planList.forEach(function (plan) {
                    vm.selectedPlanList += plan.planName + ' '
                });
            }
            vm.showList = !vm.showList;
            vm.showPreview = !vm.showPreview;
        },
        onlinePreview: function () {
            var url = '../devAmPlan/' + vm.overviewParam.action + '?yearly=' + new Date(vm.overviewParam.yearly).getFullYear();
            if (vm.selectedPlanIds && vm.selectedPlanIds.length > 0) {
                // 概览年度
                url += '&list=' + vm.selectedPlanIds;
            }
            window.open(url, vm.overviewParam.action == 'onlinePreview' ? '_blank' : '');
            vm.showList = !vm.showList;
            vm.showPreview = !vm.showPreview;
        },
        // 维护计划实施跟踪
        planImplementFollowPreview: function () {
            var id = getSelectedRow('#jqGrid');
            if (!id) {
                return;
            }
            // 只可以查看已审批通过的设备维护计划实施跟踪情况
            var data = getSelectedRowData('#jqGrid');
            if (data.status != '5') {
                layer.alert('只可以查看已审批通过的设备维护计划实施跟踪情况！', {icon: 5});
                return;
            }
            window.open('../devAmPlan/follow?id=' + id, '_blank');
        },
        loadDevLineListData: function () {
            Ajax.request({
                url: '../sys/user/treeDeptBySCXLevel?level=3',
                async: false,
                successCallback: function (r) {
                    vm.treeList = r.list;
                }
            });
        },
        initDevLineTree: function () {
            //加载分类树
            ztree = $.fn.zTree.init($("#categoryTree"), setting, vm.treeList);
            ztree.expandAll(true);
        },
        showLine: function (param) {
            openWindow({
                title: "选择产线级",
                area: ['300px', '450px'],
                content: jQuery("#categoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var nodes = ztree.getSelectedNodes();
                    if (nodes[0].deptLevel === 3) {
                        vm.devPlanMain.devLineId = nodes[0].deptId;
                        vm.devPlanMain.devLineName = nodes[0].name;
                        layer.close(index);
                    } else {
                        alert("请选择产线");
                    }
                }
            });
        },
        //车间审核
        apply: function () {
            var id = getSelectedRow("#jqGrid");
            if (!id) {
                return;
            }
            var data = getSelectedRowData("#jqGrid");
            if (data.status != '1') {
                alert("只可以审核处于[待审核]状态的维护计划！");
            } else {
                // 构建审批参数
                vm.approveParam = {
                    approveIdList: [id],
                    status: '1',
                    remark: ''
                }
                openWindow({
                    title: "审核表达",
                    area: ['450px', '300px'],
                    content: jQuery("#reviewLayer"),
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        if (typeof (vm.approveParam.status) == 'undefined') {
                            alert("请选择审核状态");
                            return;
                        }
                        Ajax.request({
                            url: '../devAmPlan/apply',
                            params: JSON.stringify(vm.approveParam),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                    layer.closeAll();
                                });
                            }
                        });

                    }
                });
            }
        },
        viewPlan: function (e) {
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-list-ol"></i> 设备维护计划详情',
                content: '../device/showAmPlanItem.html?' + e + '&true',
                btn: ['取消'],
            })
        },
        overview: function (e) {
            // 概览编制设备信息
            openWindow({
                type: 2,
                title: '<i class="fa fa-list-ol"></i> 设备编制情况概览',
                content: '../device/device_overview.html',
                btn: ['取消']
            })
        },
        adjust: function (e) {
            // 系统自动进行维护计划执行调整
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var status = getSelectedRowData("#jqGrid").status;
            if (status != '0' && status != '4') {
                iview.Message.error("维护计划审核中或已通过，不允许再次调整！");
                return;
            }
            confirm('此操作将重置当前计划的所有已调整内容，是否继续？', function () {
                Ajax.request({
                    url: "../devAmPlan/autoAdjust/" + id,
                    async: false,
                    successCallback: function (r) {
                        alert('自动调整维护计划成功', function (index) {
                            vm.reload();
                            layer.close(index)
                        });
                    }
                });
            });
        },
        submitApprove: function (e) {
            // 提交审核
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            var status = getSelectedRowData("#jqGrid").status;
            if (status == '1') {
                iview.Message.error("审核中,请耐心等待!");
                return;
            }
            if (status == '5') {
                iview.Message.error("计划已通过审核，无需重复提交");
                return;
            }
            Ajax.request({
                url: "../devAmPlan/submitApprove/" + id,
                async: false,
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                        layer.close(index)
                    });
                }
            });
        },
        planChange: function (e, planStatus) {
            //计划调整
            openWindow({
                type: 2,
                title: '<i class="fa fa-list-ol"></i>计划调整',
                content: '../device/adjustAmPlan.html?' + e + '&false',
                maxmin: true,
                btn: ['确认调整', '取消调整'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var planItemList = iframeWin.getDatas();
                    if (planItemList.length == 0) {
                        alert("调整列表为空!");
                        return;
                    }
                    var data = [];
                    for (let i = 0; i < planItemList.length; i++) {
                        data.push({
                            devMaintenancePlanItemIds: planItemList[i].itemId,
                            monthNum: planItemList[i].monthNum,
                            dayNum: planItemList[i].dayNum
                        })
                    }
                    if (data.length == 0) {
                        alert("调整列表为空!");
                        return;
                    }
                    Ajax.request({
                        url: "../devAmPlanItem/updateDay",
                        params: JSON.stringify(data),
                        async: false,
                        type: "POST",
                        contentType: "application/json",
                        successCallback: function (r) {
                            alert('操作成功', function () {
                                vm.reload();
                                layer.close(index);
                            });
                        }
                    });
                }
            })
        },
        addPlanOp: function (planId, planStatus) {
            //获取审批通过规程
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-list-ol"></i>已关联自主维护规程',
                content: '../device/devAmPlanRuleMap.html?planId=' + planId + '&status=' + planStatus,
                btn: ['取消']
            })
        },
        query: function () {
            vm.reload();
        },

        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.devPlanMain = {
                startDate: '',
                endDate: '',
                remark: '',
                planName: '',
                devLineId: '', // 关联产线ID
                devLineName: '', // 关联产线名称，展示用
                id: ''
            };
            // 初始化设备产线树插件
            vm.initDevLineTree();
        },
        update: function (event) {
            let id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id);
        },
        doHandleExcludeRange(value, valueType) {
            this.devPlanMain.excludeRange = value;
        },
        saveOrUpdate: function (event) {
            let url = vm.devPlanMain.id == (null || '') ? "../devAmPlan/save" : "../devAmPlan/update";
            if (vm.devPlanMain.startDate) {
                vm.devPlanMain.startDate = gmt2DateStr(vm.devPlanMain.startDate);
            }
            if (vm.devPlanMain.endDate) {
                vm.devPlanMain.endDate = gmt2DateStr(vm.devPlanMain.endDate);
            }
            // 由于用户未选择排除区间时是数组，选择后是字符串，所有需要针对是数组的场景处理下数据
            if (isArray(vm.devPlanMain.excludeRange)) {
                for (let i = 0; i < vm.devPlanMain.excludeRange.length; i++) {
                    vm.devPlanMain.excludeRange[i] = gmt2DateStr(vm.devPlanMain.excludeRange[i])
                }
                vm.devPlanMain.excludeRange = vm.devPlanMain.excludeRange.join(',');
            }
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.devPlanMain),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            let ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../devAmPlan/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../devAmPlan/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.devPlanMain = r.devPlanMain;
                }
            });
        },
        reload: function (event) {
            // 清空postData缓存数据
            var postData = $("#jqGrid").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var queryParam = {};
            if (vm.q.planName) {
                queryParam.planName = vm.q.planName;
            }
            if (vm.q.deptCode) {
                queryParam.deptCode = vm.q.deptCode;
            }
            if (vm.q.yearly) {
                queryParam.yearly = gmt2YearStr(vm.q.yearly);
            }
            vm.showList = true;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: queryParam,
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                deptCode: '',
                yearly: ''
            };
            // 取消选中的
            deptZtree.cancelSelectedNode();
            vm.reload();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});
